package org.lzy.shop.feedback


import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.google.android.material.chip.Chip
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.hjq.permissions.permission.PermissionLists
import com.hjq.permissions.permission.base.IPermission
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.lzy.shop.Constant
import org.lzy.shop.R
import org.lzy.shop.adapter.ChoosePicAdapter
import org.lzy.shop.base.BaseMvvmActivity
import org.lzy.shop.databinding.ActivityFeedbackSubmitBinding
import org.lzy.shop.databinding.LayoutFeedbackChipItemBinding
import org.lzy.shop.datas.FeedBackSubmitRequest
import org.lzy.shop.response.FeedbackType
import org.lzy.shop.util.BitmapUtils.pathToBitmap
import org.lzy.shop.util.DataStoreUtils
import org.lzy.shop.util.FileManager
import org.lzy.shop.view.TakePhoto
import org.lzy.shop.viewmodel.FeedBackModel
import top.zibin.luban.OnCompressListener
import java.io.File
import java.lang.ref.WeakReference

/**
 * 提交反馈
 */
class FeedBackSubmitActivity : BaseMvvmActivity<ActivityFeedbackSubmitBinding, FeedBackModel>({ ActivityFeedbackSubmitBinding.inflate(it) }){
    private  var mTypeFeedBackId: Int = 0
    private var mChoosePicAdapter: ChoosePicAdapter? = null

    private var takePhoto: TakePhoto? = null

    private val mFeedBackType= mutableListOf<FeedbackType>()

    //相册回调
    var mActivityResultLauncherAlbum: ActivityResultLauncher<Intent>? = null

    //选择的相册图片以Uri格式丢数组
   private var selectedFilesAll = ArrayList<Uri>()

    //一张张图片上传后添加到这个数组直接丢给后台
    private val uploadLocalPaths: MutableList<String> = mutableListOf()

    //压缩后的图片路径
    private val compressedImagePaths = mutableListOf<String>()


    override fun initView() {
        setTitleText(getResString(R.string.feedback_new))
        takePhoto = TakePhoto(WeakReference(this))
        registerActivityResult()
        mChoosePicAdapter = ChoosePicAdapter(this, 3)
        binding.feedbackPicRv.apply {
            layoutManager= GridLayoutManager(this@FeedBackSubmitActivity, 3)
            adapter=mChoosePicAdapter
            layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
            setHasFixedSize(false)
        }

        mChoosePicAdapter?.setOnAddPicturesListener(object : ChoosePicAdapter.OnAddPicturesListener {
            override fun onAdd() {
                //检查是否已达到最大选择数量
                if (selectedFilesAll.size >= 9) {
                    showToast("最多只能选择9张图片")
                    return
                }
                openAlbum()
            }

            override fun delete(position: Int) {
                //移除图片
                if (position < selectedFilesAll.size) {
                    selectedFilesAll.removeAt(position)
                }
                if (position < compressedImagePaths.size) {
                    compressedImagePaths.removeAt(position)
                }
                mChoosePicAdapter?.removeImage(position)
            }
        })

    }

    //打开相册，打开前要申请动态权限
    fun openAlbum(){
        XXPermissions.with(this)
            // 申请多个权限
            .permission(PermissionLists.getManageExternalStoragePermission())
            .permission(PermissionLists.getCameraPermission())
            .request(object : OnPermissionCallback {

                override fun onGranted(permissions: MutableList<IPermission>, allGranted: Boolean) {
                    if (!allGranted) {
                        return
                    }
                    // 使用Intent.ACTION_GET_CONTENT支持多选
                    val intentAlbum = Intent(Intent.ACTION_GET_CONTENT)
                    intentAlbum.type = "image/*"
                    intentAlbum.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
                    intentAlbum.addCategory(Intent.CATEGORY_OPENABLE)
                    mActivityResultLauncherAlbum?.launch(intentAlbum)
                }

                override fun onDenied(permissions: MutableList<IPermission>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(this@FeedBackSubmitActivity, permissions)
                    } else {

                    }
                }
            })
    }
    private fun registerActivityResult() {
        mActivityResultLauncherAlbum = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                // 使用协程处理图片，避免UI线程阻塞
                lifecycleScope.launch(Dispatchers.IO) {
                    val clipData = result.data?.clipData
                    if (clipData != null) {
                        //处理多选情况
                        val count = clipData.itemCount
                        val remainingSlots = 9 - selectedFilesAll.size
                        val actualCount = count.coerceAtMost(remainingSlots)

                        if (actualCount <= 0) {
                            withContext(Dispatchers.Main) {
                                showToast("最多只能选择9张图片")
                            }
                            return@launch
                        }

                        for (i in 0 until actualCount) {
                            val uri = clipData.getItemAt(i).uri
                            if (uri != null) {
                                selectedFilesAll.add(uri)
                                handleSelectedImage(uri)
                            }
                        }
                    } else if (result.data?.data != null) {
                        //处理单选情况
                        val uri = result.data?.data
                        if (uri != null && selectedFilesAll.size < 9) {
                            selectedFilesAll.add(uri)
                            handleSelectedImage(uri)
                        } else if (selectedFilesAll.size >= 9) {
                            withContext(Dispatchers.Main) {
                                showToast("最多只能选择9张图片")
                            }
                        }
                    }
                }
            }
        }
    }

    //处理选择的图片，进行压缩并显示
    private fun handleSelectedImage(uri: Uri) {
        val file: File? = FileManager.getMediaUri2File(this, uri)
        val filePath = file?.absolutePath

        if (!TextUtils.isEmpty(filePath)) {
            lifecycleScope.launch(Dispatchers.IO) {
                try {
                    val file: File? = FileManager.getMediaUri2File(this@FeedBackSubmitActivity, uri)
                    val filePath = file?.absolutePath

                    if (!TextUtils.isEmpty(filePath)) {
                        // 创建一个CompletableDeferred来等待图片压缩完成
                        val compressedFileDeferred = CompletableDeferred<File?>()

                        // 仍然使用现有的压缩机制，但在IO线程中执行
                        withContext(Dispatchers.Main) {
                            takePhoto?.compressPicture(filePath, object : OnCompressListener {
                                override fun onStart() {
                                    // 可以添加加载提示
                                    Log.d("FeedBackSubmit", "开始压缩图片")
                                }

                                override fun onSuccess(compressedFile: File?) {
                                    compressedFileDeferred.complete(compressedFile)
                                }

                                override fun onError(e: Throwable?) {
                                    Log.e("FeedBackSubmit", "图片压缩失败", e)
                                    compressedFileDeferred.completeExceptionally(e ?: Exception("图片压缩失败"))
                                }
                            })
                        }

                        // 等待压缩完成
                        val compressedFile = compressedFileDeferred.await()

                        if (compressedFile != null && compressedFile.exists()) {
                            // 在UI线程更新界面
                            withContext(Dispatchers.Main) {
                                try {
                                    // 优化：使用Coil或其他图片加载库代替直接加载Bitmap
                                    // 这里使用try-catch确保即使图片处理失败也不会崩溃
                                    val bitmap = pathToBitmap(compressedFile.absolutePath)
                                    mChoosePicAdapter?.addImage(bitmap)
                                    compressedImagePaths.add(compressedFile.absolutePath)
                                } catch (e: Exception) {
                                    Log.e("FeedBackSubmit", "图片处理失败", e)
                                    showToast("图片处理失败")
                                }
                            }
                        }
                    }
                } catch (e: Exception) {
                    // 捕获所有异常，确保应用不会崩溃
                    Log.e("FeedBackSubmit", "处理图片时发生异常", e)
                    withContext(Dispatchers.Main) {
                        showToast("处理图片失败，请重试")
                    }
                }
            }
        }
    }


    override fun initData() {
        mViewModel.getFeedBackTypeData.observeWithLifecycle(this){feedbackTypes ->
            feedbackTypes?.let {
                mFeedBackType.clear()
                mFeedBackType.addAll(feedbackTypes)
                for (index in 0 until feedbackTypes.size) {
                    var  chipItem: Chip
                    //这里也要需要判断一下复用的情况
                    val childCount = binding.chipGroup.childCount
                    if (index < childCount) {
                        chipItem = binding.chipGroup.getChildAt(index) as Chip
                    } else {
                        chipItem = createChipItem()
                        binding.chipGroup.addView(chipItem)
                    }
                    chipItem.text = feedbackTypes[index].name
                }
                binding.chipGroup.setOnCheckedChangeListener { group, checkedId ->
                    for (index in 0 until binding.chipGroup.childCount) {
                        if (binding.chipGroup.getChildAt(index)?.id == checkedId) {
                            mTypeFeedBackId = feedbackTypes[index].value
                            break
                        }else{
                            mTypeFeedBackId=0
                        }
                    }
                }
            }
        }
         //获取腾讯OSS凭证回调
        mViewModel.ossUploadLiveData.observeWithLifecycle(this){ossUpload ->
            dismissLoading()
            ossUpload?.let {
              mViewModel.uploadImages(this,selectedFilesAll,
                  ossUpload.url,
                  ossUpload.credentials.tmpSecretId,
                  ossUpload.credentials.tmpSecretKey,
                  ossUpload.credentials.sessionToken,
                  )
            }

        }

        //图片上传成功返回URL回调
        mViewModel.uploadImgLiveData.observeWithLifecycle(this){localPath ->
            Log.e("uploadUrl", "图片上传成功返回URL: ，${localPath}")
            localPath?.let {
                uploadLocalPaths.clear()
                uploadLocalPaths.add(it) }
            val feedBackSubmitRequest = FeedBackSubmitRequest(DataStoreUtils.getString(Constant.MOBILE),
                binding.input.text.toString(),uploadLocalPaths,mTypeFeedBackId)
            mViewModel.feedBackSubmit(feedBackSubmitRequest)
        }

        mViewModel.getFeedBackSubmitData.observe(this){
            dismissLoading()
            showToast("操作成功")
        }

    }


    /**
     * 创建Chip
     */
    fun createChipItem(): Chip {
        val chipItem: Chip = LayoutFeedbackChipItemBinding.inflate(LayoutInflater.from(this), binding.chipGroup, false).root
        //刚创建的时候是没有选中的
        chipItem.isChecked=false
        chipItem.isCheckable=true
        chipItem.setOnCheckedChangeListener { p0, p1 ->
            if (p1) {
                chipItem.setTextColor(Color.WHITE)
                chipItem.setChipBackgroundColorResource(R.color.colorPrimary)
            }else{
                chipItem.setTextColor(Color.BLACK)
                chipItem.setChipBackgroundColorResource(R.color.Surface)
            }
        }
        chipItem.id= binding.chipGroup.childCount
        return chipItem
    }

    override fun requestData() {
        getFeedBackType()

    }

    //获取反馈类型
    fun getFeedBackType(){
        mViewModel.getReasonData()

    }

    override fun allClick() {
        binding.feebackSubmitBtn.setOnClickListener {
            if (mTypeFeedBackId<=0) {
                showToast(getResString(R.string.feedback_choosetype))
            }else if (TextUtils.isEmpty(binding.input.text.toString())) {
                showToast(getResString(R.string.feedback_content_input))
            }else{
                submit()
            }
        }
    }

    private fun submit() {
        showLoading()
        mViewModel.getTencentCredentials()
    }


    override fun onDestroy() {
        super.onDestroy()
        //清理资源
        releaseBitmapResources()
        // 修复：调用adapter的releaseResources方法释放图片资源
        mChoosePicAdapter?.releaseResources()
        mChoosePicAdapter = null
        mActivityResultLauncherAlbum = null
        takePhoto = null
    }

    private fun releaseBitmapResources() {
        // 清理URI集合
        selectedFilesAll.clear()

        // 清理压缩文件路径集合
        compressedImagePaths.clear()
    }
}